package top.kpromise.user.crash;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.kpromise.user.response.Result;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String, Object> defaultExceptionHandler(HttpServletRequest request, Exception e) {
        Map<String, Object> handlerErrorResult = handlerError(e);
        if (handlerErrorResult != null) {
            return handlerErrorResult;
        }
        e.printStackTrace();
        System.out.println("uri " + request.getRequestURI());
        ObjectMapper objectMapper = new ObjectMapper();
        String params = "{}";
        try {
            params = objectMapper.writeValueAsString(request.getParameterMap());
        }catch (Exception param) {
            param.printStackTrace();
        }
        if (params.equals("{}")) {
            params = getRequestJson(request);
        }
        String title = request.getRequestURI();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String crashTime = df.format(new Date());
        String text = "#### API 请求失败 @13067856109\n" +
                "> url " + request.getRequestURI() + "\n\n" +
                "> 请求参数 \n" + params + "\n\n" +
                "> 堆栈信息 \n" + e.getMessage() + "\n\n" +
                "> ###### 出错时间 " + crashTime + " \n";
        ArrayList<String> phones = new ArrayList<>();
        phones.add("13067856109");
        //new DingTalkMessage(new DingTalkMessageBuilder().markdownMessage(title, text).at(phones)).send();
        //CrashHandler.reportException(e);
        return Result.data(null, "系统异常，请联系客服");
    }

    private static String getRequestJsonString(HttpServletRequest request)
            throws Exception {
        String submitMethod = request.getMethod().toUpperCase();
        if (submitMethod.equals("GET")) {
            return new String(request.getQueryString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8)
                    .replaceAll("%22", "\"");
        } else {
            return getRequestPostStr(request);
        }
    }

    private static Map<String, Object> handlerError(Exception e) {
        if (e instanceof MissingRequestHeaderException) {
            if (e.getMessage() != null && e.getMessage().startsWith("Missing request header 'userId'")) {
                return Result.data(null, "用户未登录或登录过期");
            }
        }
        return null;
    }

    private static String getRequestJson(HttpServletRequest request) {
        try {
            return getRequestJsonString(request);
        } catch (Exception e) {
            return null;
        }
    }

    private static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if (contentLength < 0) {
            return null;
        }
        byte[] buffer = new byte[contentLength];
        for (int i = 0; i < contentLength; ) {
            int readLen = request.getInputStream().read(buffer, i, contentLength - i);
            if (readLen == -1) {
                break;
            }
            i += readLen;
        }
        return buffer;
    }

    private static String getRequestPostStr(HttpServletRequest request)
            throws Exception {
        byte[] buffer = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        if (buffer == null) {
            return "{}";
        }
        return new String(buffer, charEncoding);
    }
}
